package com.gdyd.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
@Deprecated
//@Configuration    使用starter来实现
public class MyDataSourceConfig {

    //默认的自动配置是判断容器中没有才会配@ConditionalOnMissingBean(DataSource.class)
    //在容器中加入DruidDataSource，容器中就不会配HikariDataSource
    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
    /*  这些属性可以在application.yaml中的spring.datasource中配置
        druidDataSource.setUrl();
        druidDataSource.setDriverClassName();
        druidDataSource.setUsername();
        druidDataSource.setPassword();
        druidDataSource.setMaxActive();*/
        //加入监控功能
        druidDataSource.setFilters("stat,wall");    //执行sql操作才会有记录
        return druidDataSource;
    }

    /**
     * 配置Druid的监控页功能
     * @return
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet(){
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        registrationBean.addInitParameter("loginUsername","admin");
        registrationBean.addInitParameter("loginPassword","123456");
        return  registrationBean;
    }

    /**
     * 开启Web应用：WebStatFilter用于采集web-jdbc关联监控的数据
     * 统计每一个请求查数据库的信息
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        //拦截所有请求
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        //排除非数据库访问请求
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,/swagger-ui.html");
        return filterRegistrationBean;
    }
}
